import React, { Component } from 'react'
import queryString from 'query-string'
import moment from 'moment'
import { withRouter } from 'react-router'
import { Link } from 'react-router-dom'
import styles from './style.module.scss'
import ContentSideNav from '../../components/common/ContentSideNav'
import Page from '../../components/common/Page'
import Crumbs from '../../components/common/Crumbs'
import ask from '../../serve/api';

export default withRouter(class Result extends Component {

  constructor(props){
    super();
    this.state = {
      contentSideNavList : [],
      contentList : [],
      totalPage : 0,
      contentPage : 1,
      contentPageSize : 10,
      typeId : undefined,
      resultData : {
        inputVal : '',
        searchTypes : {
          index : 0,
          list : [{
            name : '发布日期降序',
            code : 0,
          },{
            name : '发布日期升序',
            code : 1,
          }]
        },
      },
    }
  }

  componentDidMount() {
    // 获取类型列表
    this.fetchTypeList().then(()=>{
      // 设置nav id
      this.setTypeId(()=>{
        // 获取列表
        this.fetchItemList();
      });
    });
  }

  componentDidUpdate(prevProps, prevState) {
    if(this.props.location !== prevProps.location){
      // 设置nav id
      this.setTypeId(()=>{
        // 获取列表
        this.fetchItemList();
      });
      
    };
  }

  setTypeId = (callback)=>{
    const {location} = this.props;
    const oSearch = queryString.parse(location.search);
    const typeId = oSearch.id? oSearch.id : this.state.contentSideNavList[0]? this.state.contentSideNavList[0].id : undefined;
    this.setState({
      typeId,
    }, callback);
  }

  async fetchTypeList(){
    // 获取类型列表
    const {code, result} = await ask.fetchListResultTypeAll();
    try {
      if(code !== '000000'){
        throw new Error('数据出错');
      };

      const contentSideNavList = result.map(item => {
        return {
          title : item.name,
          id : item.id,
        }
      });
      this.setState({
        contentSideNavList,
      });
    } catch (error) {
      console.log(error);
    }
  }

  async fetchItemList(){

    const {resultData} = this.state;

    const searchKey = resultData.inputVal.trim()? resultData.inputVal.trim() : undefined;
    // 获取列表
    const {code, result, resultNum} = await ask.fetchListTtResult({
      typeId : this.state.typeId,
      page : this.state.contentPage,
      pageSize : this.state.contentPageSize,
      searchKey,
    });
    try {
      if(code !== '000000'){
        throw new Error('数据出错');
      };

      const contentList = Array.isArray(result)? result.map(item => {
        return {
          title : item.title || item.name,
          summary : item.summary,
          author : item.author,
          time : item.public_at,
          id : item.id,
        }
      }) : [];
      const totalPage = resultNum || 0;
      this.setState({
        contentList,
        totalPage,
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 点击类型
  itemClick = ({item, index})=>{
    this.changeRoute('id', item.id? item.id+'' : undefined);
    // 重置分页
    const {resultData} = this.state;
    resultData.inputVal = '';
    resultData.searchTypes.index = 0;
    this.setState({
      contentPage : 1,
      totalPage : 0,
      resultData,
    });
  }

  changeRoute = (propname, value)=>{
    const {history, location} = this.props;
    let oSearch = queryString.parse(location.search);
    let methods;
    if(oSearch[propname] === value){
      methods = 'replace';
    }else{
      methods = 'push';
      value? oSearch[propname] = value : delete oSearch[propname];
    };
    const search = queryString.stringify(oSearch);
    history[methods]({search});
  }

  activeKey = (val)=>{
    let index = 0;
    for(let i=0;i<this.state.contentSideNavList.length;i++){
      if(this.state.contentSideNavList[i].id + '' === val){
        index = i;
        break;
      }
    };
    return index;
  }

  // 点击分页按钮
  clickPageIndex = (contentPage)=>{
    this.setState({
      contentPage,
    },()=>{
      // 获取列表
      this.fetchItemList();
    });
  }

  // 输入框事件
  onInputChange = (e)=>{
    const {resultData} = this.state;
    resultData.inputVal = e.target.value;
    this.setState({
      resultData
    });
  }

  onSearchTypeClick =({type, index})=>{
    const {resultData} = this.state;
    resultData.searchTypes.index =  index;
    this.setState({
      resultData
    });
  }

  search = ()=>{
    this.setState({
      contentPage : 1,
    },()=>{
      this.fetchItemList();
    });
  }
  
  render() {
    const {
      contentSideNavList,
      contentList,
      totalPage,
      typeId,
      contentPage,
      resultData,
    } = this.state;

    const activeKey = this.activeKey(typeId);

    const crumbsList = [{
      name : '首页',
      path : '/mainPage',
    },{
      name : '智库数据',
      path : '/mainPage/thinkTankData',
    },{
      name : '智库成果',
    }];

    return (
      <div className={styles.result_wrap}>
        {/* 面包屑 */}
        <Crumbs list={crumbsList} />

        <div className={styles.forum_wrap}>
          <div className={styles.sidebar}>
            <ContentSideNav activeKey={activeKey} list={contentSideNavList} onItemClick={this.itemClick} />
          </div>
          <div className={styles.mainwrap}>
            <div className={styles.result_main}>
              <div className={styles.head}>
                <span className={styles.tit}>关键字：<input className={styles.inp} type="text" placeholder="请输入关键字" value={resultData.inputVal}  onChange={ e => { this.onInputChange(e); }} /></span>
                <div className={styles.con}>
                  <span className={styles.checkboxwrap}>
                    {
                      resultData.searchTypes.list.map( (type, index) => <a key={index} className={index === resultData.searchTypes.index? styles.on : ''} onClick={()=>{ this.onSearchTypeClick({type, index}); }}><em></em><i>{type.name}</i></a> )
                    }
                  </span>
                  <a className={styles.searchbtn} onClick={this.search}>搜索</a>
                </div>
              </div>
              { !!contentList.length && (
                <ul className={styles.commonlist}>
                  { contentList.map((item, index)=> <li key={index}>
                    <Link to={`/mainPage/commonDetail/result/${item.id}`}  title={item.title}>
                      <p dangerouslySetInnerHTML={{__html : item.title}}></p>
                      <p dangerouslySetInnerHTML={{__html : '作者：'+item.author}}></p>
                      <p dangerouslySetInnerHTML={{__html : item.summary}}></p>
                    </Link>
                    <span className={styles.date}>{moment(item.time).format('YYYY-MM-DD')}</span>
                  </li> ) }
                </ul>
              )}
              { !contentList.length && <p className={styles.nodata}>暂无相关数据</p> }
            </div>
            { !!totalPage && <Page 
              pageConfig={{totalPage, currentPage : contentPage}}
              pageCallbackFn={this.clickPageIndex}
            />}
          </div>
        </div>

      </div>
      
    )
  }
})
